package com.kedacom.demo.emailgateway.service;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.kedacom.demo.emailgateway.core.annotation.Properties;
import com.kedacom.demo.emailgateway.dao.EmailDao;
import com.kedacom.demo.emailgateway.exception.BusinessException;
import com.kedacom.demo.emailgateway.model.Email;
import com.kedacom.demo.emailgateway.model.EmailHistory;
import com.kedacom.demo.emailgateway.model.UnderwayEmail;
import com.kedacom.demo.emailgateway.model.UnderwayEmailSendToManyUser;
import com.kedacom.demo.emailgateway.util.TimeUtil;

/**
 * 发送邮件
 * 
 * @author wengxiongfei
 * @date 2013-12-5 下午3:47:38
 * @note EmailGatewayServerImpl
 */
@Component("emailGatewayServer")
public class EmailGatewayServerImpl implements EmailGatewayServer {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Properties(name = "app.mail.server.from")
	private String from;

	@Resource
	EmailDao emailDao;
	@Resource
	EmailGatewayHelper emailGatewayHelper;

	@Override
	public void handleMessage(Email email) {
		logger.debug("##############handlerMessage start ###########");
		email.setFrom(from);
		email.setCreateDateTime(TimeUtil.getCurrentTime());
		UnderwayEmail underwayEmail = new UnderwayEmail();
		BeanUtils.copyProperties(email, underwayEmail);
		underwayEmail.setCreateDateTime(email.getCreateDateTime());
		underwayEmail.setNum(1);

		try {
			if (!underwayEmail.getTo().startsWith(",") && underwayEmail.getTo().split(",").length > 1) {
				UnderwayEmailSendToManyUser sendToManay = new UnderwayEmailSendToManyUser();
				BeanUtils.copyProperties(underwayEmail, sendToManay);
				emailGatewayHelper.sendMimeMailByMailSender(sendToManay);
			} else {
				emailGatewayHelper.sendMimeMailByMailSender(underwayEmail);
			}
			logger.debug("############发送成功");
			onSendSucess(underwayEmail);
		} catch (BusinessException be) {
			underwayEmail.setRemarks(be.getMessage());
			onSendSucess(underwayEmail);
		} catch (Exception e) {
			onSendFailure(underwayEmail);
			logger.debug("exception = " + e.getMessage());
		}
		logger.debug("##############handlerMessage over ###########");
	}

	/**
	 * 发送成功
	 * 
	 * @param email
	 */
	private void onSendSucess(UnderwayEmail email) {
		EmailHistory emailHistory = new EmailHistory();
		BeanUtils.copyProperties(email, emailHistory);
		emailHistory.setSendDateTime(TimeUtil.getCurrentTime());
		emailDao.saveHistoryEmail(emailHistory);
	}

	/**
	 * 发送失败
	 * 
	 * @param email
	 */
	private void onSendFailure(Email email) {
		emailDao.saveEmail(email);
	}
}
